function food(x, y, crop)
 {
    this.life = 0;
    this.hue = 128;
    this.energy = Math.sqrt(maxFoodValue);
    this.crop = crop;
    this.x = x;
    this.y = y;

    {
        var f = this;
        this.interval = setInterval(function(){grow(f);},Math.random()*foodGrowthRate);
    }
    
    this.draw = function(context, viewport)
    {
        if (this.x > viewport.left && this.x < viewport.right && this.y > viewport.top && this.y < viewport.bottom)
        {
            //context.fillStyle = 'green';
            context.fillStyle = 'hsl(' + this.hue + ', 90%, 50%)';
            w = Math.sqrt(this.energy);
            context.fillRect(this.x - w / 2 - viewport.left, this.y - w / 2 - viewport.top, w, w);
        }
    };
 }
 
function grow(f)
{
    if (Math.random() > 0.5)
    {
        if (f.crop.length < f.crop.maxFood)
        {
            f.crop.push(new food(f.x + dist*(1-2*Math.random()), f.y + dist*(1-2*Math.random()), f.crop));
        }
    }
    else
    {
        if (f.energy < maxFoodValue)
            f.energy += 1;
    }
}

function CropField(maxFood)
{
    this.maxFood = maxFood;
}

CropField.prototype = new Array();

CropField.prototype.remove = function(index)
{
    clearInterval(this[index].interval);
    var oldX = this[index].x;
    var oldY = this[index].y;
    this.splice(index,1);
    if ( this.length < 1 )
    {
        this.push(new food(oldX,oldY, this));
    }
}

function fit(object, fitmode)
{
    with (object)
    {
        if (fitmode == "torus")
        {
            if (x > maxX) x = x - maxX;
            if (x < 0) x = maxX - x;
            if (y > maxY) y = y - maxY;
            if (y < 0) y = maxY - y;
        }
        if (fitmode == "kill")
        {
            if (x > maxX) {x = maxX - (x - maxX); if (energy) energy*=0.9;}
            if (x < 0) {x = - x; if (energy) energy*=0.9;}
            if (y > maxY) {y = maxY - (y - maxY); if (energy) energy*=0.9;}
            if (y < 0) {y = - y; if (energy) energy*=0.9;}
        }
        else if (fitmode == "bounce")
        {
            if (x > maxX) x = maxX - (x - maxX);
            if (x < 0) x = - x;
            if (y > maxY) y = maxY - (y - maxY);
            if (y < 0) y = - y;
        }
        else //clip
        {
            if (x > maxX) x = maxX;
            if (x < 0) x = 0;
            if (y > maxY) y = maxY;
            if (y < 0) y = 0;
        }
    }
}